package com.gnuc.thoth.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.gnuc.thoth.R;
import com.gnuc.thoth.framework.Thoth;
import com.gnuc.thoth.framework.ThothLog;
import com.gnuc.thoth.framework.auth.ThothAuth;
import com.gnuc.thoth.framework.callbacks.ThothAccountCallback;
import com.gnuc.thoth.framework.callbacks.ThothCallback;
import com.gnuc.thoth.framework.callbacks.ThothRequestCallback;
import com.gnuc.thoth.service.listeners.RequestListener;

public class SetupMain extends Activity
{
	private static SetupMain	instance					= null;
	ViewFlipper						sF							= null;
	Button							bt							= null;
	Button							gmbt						= null;
	Button							gmbtno					= null;
	Button							gcbt						= null;
	Button							gcbtno					= null;
	ProgressBar						pb							= null;
	ProgressBar						pSPB						= null;
	static boolean					SETUP_CALL_CAPTURE	= true;
	static boolean					SETUP_MSGS_CAPTURE	= true;
	static boolean					SETUP_MSGM_CAPTURE	= true;
	static boolean					SETUP_DATA_CAPTURE	= true;
	static boolean					captureTimeout			= false;
	public volatile static int	sPbMax					= 1;
	public volatile static int	sPbCurrent				= 0;
	Intent							intent					= null;
	
	public static SetupMain getInstance()
	{
		if (instance == null)
			instance = new SetupMain();
		return instance;
	}
	
	public static void gc()
	{
		instance = null;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		try
		{
			setContentView(R.layout.setup_layout);
			bt = (Button) findViewById(R.id.setup_bt);
			pb = (ProgressBar) findViewById(R.id.setup_pb);
			sF = (ViewFlipper) findViewById(R.id.setup_flipper);
			sF.setInAnimation(Thoth.cx, android.R.anim.fade_in);
			sF.setOutAnimation(Thoth.cx, android.R.anim.fade_out);
			intent = getIntent();
			bt.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					bt.setVisibility(View.GONE);
					if (sF.getDisplayedChild() == 0)
					{
						final Account[] accounts = AccountManager.get(Thoth.cx).getAccountsByType("com.google");
						final List<String> accountNames = new ArrayList<String>();
						for (Account account : accounts)
							accountNames.add(account.name);
						ListView accountList = (ListView) findViewById(R.id.st_account_list);
						accountList.setAdapter(new ArrayAdapter<String>(Thoth.cx, android.R.layout.simple_expandable_list_item_1, accountNames));
						accountList.setDivider(getResources().getDrawable(R.drawable.row_gradient1));
						accountList.setDividerHeight(1);
						accountList.setOnItemClickListener(new OnItemClickListener()
						{
							@Override
							public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
							{
								view.setVisibility(View.GONE);
								Thoth.Settings.USR_DEVICE_ACCOUNT = accounts[pos].hashCode();
								Thoth.Settings.USR_DEVICE_ACCOUNT_EMAIL = accounts[pos].name;
								Thoth.Settings.write();
								checkAccount(accounts[pos]);
							}
						});
						sF.setDisplayedChild(1);
					}
				}
			});
		}
		catch (Exception e)
		{
			ThothLog.e(e);
			Main.getInstance().mainHandler.sendEmptyMessage(-1);
		}
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		Thoth.cx = this;
		instance = this;
		Thoth.Settings.read();
		if (sF.getDisplayedChild() == 0)
			hdlr.sendEmptyMessage(0);
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		Thoth.Settings.write();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		super.onKeyDown(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			switch (sF.getDisplayedChild())
			{
				case 0 :
					return true;
				case 1 :
					sF.setDisplayedChild(0);
					bt.setVisibility(View.VISIBLE);
					return false;
				case 2 :
					Toast.makeText(Thoth.cx, "Please wait until the setup process completes.", Toast.LENGTH_SHORT).show();
					return false;
				case 3 :
					return false;
				case 4 :
					promptGoogleMailSync();
					return false;
			}
		}
		return true;
	}
	
	public Handler	hdlr	= new Handler()
								{
									@Override
									public void handleMessage(final Message msg)
									{
										try
										{
											switch (msg.what)
											{
												case 0 :
												{
													if (Thoth.Settings.APP_NETWORK_CONFIGURE && Thoth.wasNetworkSwitchedOn())
													{
														Thoth.showProgressDialog(new ThothCallback()
														{
															@Override
															public void handle(boolean result)
															{
																hdlr.sendEmptyMessageDelayed(result ? 1 : 0, 2000);
															}
														}, true);
													}
													else if (Thoth.isNetworkOK())
														hdlr.sendEmptyMessage(1);
													else
													{
														Thoth.switchOnNetwork(0, new ThothCallback()
														{
															@Override
															public void handle(boolean result)
															{
																if (result)
																	hdlr.sendEmptyMessage(1);
																else
																{
																	runOnUiThread(new Runnable()
																	{
																		@Override
																		public void run()
																		{
																			AlertDialog.Builder adb = new AlertDialog.Builder(Thoth.cx);
																			adb.setIcon(R.drawable.icon);
																			adb.setTitle("Setup Failure");
																			adb.setMessage("Cannot continue without a network connection.");
																			adb.setCancelable(false);
																			adb.setPositiveButton("Retry?", new DialogInterface.OnClickListener()
																			{
																				public void onClick(DialogInterface dialog, int id)
																				{
																					hdlr.sendEmptyMessage(0);
																				}
																			});
																			adb.setNegativeButton("Later", new DialogInterface.OnClickListener()
																			{
																				public void onClick(DialogInterface dialog, int id)
																				{
																					dialog.cancel();
																					Main.getInstance().mainHandler.sendEmptyMessage(666);
																				}
																			});
																			Thoth.ad = adb.create();
																			Thoth.ad.show();
																		}
																	});
																}
															}
														});
													}
													break;
												}
												case 1 :
												{
													RequestListener.onReceive(Thoth.REQ.HELLO, new ThothRequestCallback()
													{
														@Override
														public void progress(int resultCode, int progressValue, final int r)
														{}
														
														@Override
														public void handle(int resultCode)
														{
															if (resultCode == 1)
																hdlr.sendEmptyMessage(2);
															else
															{
																Message msg = new Message();
																msg.what = -1;
																msg.obj = new String("Hello to Thoth server failed.");
																hdlr.sendMessage(msg);
															}
														}
													});
													break;
												}
												case 2 :
												{
													runOnUiThread(new Runnable()
													{
														@Override
														public void run()
														{
															bt.setVisibility(View.VISIBLE);
															pb.setVisibility(View.GONE);
															pSPB = (ProgressBar) findViewById(R.id.st_set_account_1_pb2);
															Thoth.sendToService(Thoth.REQ.CALL_CAPTURE, null, null);
															Thoth.sendToService(Thoth.REQ.MSGS_CAPTURE, null, null);
															Thoth.sendToService(Thoth.REQ.MSGM_CAPTURE, null, null);
															Thoth.sendToService(Thoth.REQ.DATA_CAPTURE, null, null);
														}
													});
													break;
												}
												case 3 :
												{
													connect();
													break;
												}
												case 4 :
												{
													createUser();
													break;
												}
												case 5 :
												{
													editUser();
													break;
												}
												case 6 :
												{
													promptGoogleMailSync();
													break;
												}
												case 7 :
												{
													promptGoogleCalendarSync();
													break;
												}
												case 50 :
												{
													captureLogs();
													break;
												}
												case 51 : // Call capture complete
												{
													SETUP_CALL_CAPTURE = false;
													ThothLog.dL("SETUP_CALL_CAPTURE COMPLETE -> " + System.currentTimeMillis());
													break;
												}
												case 52 : // SMS capture complete
												{
													SETUP_MSGS_CAPTURE = false;
													ThothLog.dL("SETUP_MSGS_CAPTURE COMPLETE -> " + System.currentTimeMillis());
													break;
												}
												case 53 : // MMS capture complete
												{
													SETUP_MSGM_CAPTURE = false;
													ThothLog.dL("SETUP_MSGM_CAPTURE COMPLETE -> " + System.currentTimeMillis());
													break;
												}
												case 54 : // Data capture complete
												{
													SETUP_DATA_CAPTURE = false;
													ThothLog.dL("SETUP_DATA_CAPTURE COMPLETE -> " + System.currentTimeMillis());
													break;
												}
												case 55 :
												{
													runOnUiThread(new Runnable()
													{
														@Override
														public void run()
														{
															try
															{
																pSPB.setMax(sPbMax);
																pSPB.setProgress(sPbCurrent);
																if (msg.arg1 == 0)
																{
																	TextView ttv = ((TextView) findViewById(R.id.st_set_account_2_1_title));
																	ttv.setText("");
																	ttv.setText((String) msg.obj);
																}
																else if (msg.arg1 == 1)
																{
																	TextView ttv = ((TextView) findViewById(R.id.st_set_account_2_2_title));
																	ttv.setText("");
																	ttv.setText((String) msg.obj);
																}
																else if (msg.arg1 == 2)
																{
																	TextView ttv = ((TextView) findViewById(R.id.st_set_account_2_3_title));
																	ttv.setText("");
																	ttv.setText((String) msg.obj);
																}
																else if (msg.arg1 == 3)
																{
																	TextView ttv = ((TextView) findViewById(R.id.st_set_account_2_4_title));
																	ttv.setText("");
																	ttv.setText((String) msg.obj);
																}
															}
															catch (Exception e)
															{}
														}
													});
													break;
												}
												case -999 :
												{
													synchronized (this)
													{
														ThothAuth.authTimeout = true;
													};
													break;
												}
												case -888 :
												{
													synchronized (this)
													{
														captureTimeout = true;
													};
													break;
												}
												case -1 :
												{
													if (null != msg.obj) { throw new Exception((String) msg.obj); }
													break;
												}
											}
										}
										catch (Exception e)
										{
											ThothLog.e(e);
											Main.getInstance().mainHandler.sendEmptyMessage(-1);
										}
									}
								};
	
	void checkAccount(final Account account)
	{
		sF.setDisplayedChild(2);
		findViewById(R.id.st_set_account_1).setVisibility(View.VISIBLE);
		findViewById(R.id.st_set_account_1_1).setVisibility(View.VISIBLE);
		pSPB.setVisibility(View.VISIBLE);
		pSPB.setProgress(25);
		ThothAuth.checkAccount(account, new ThothAccountCallback()
		{
			@Override
			public void handle(int resultCode)
			{
				switch (resultCode)
				{
					case 0 :
					{
						runOnUiThread(new Runnable()
						{
							@Override
							public void run()
							{
								pSPB.setProgress(50);
							}
						});
						ThothAuth.authenticate(account, new ThothAccountCallback()
						{
							@Override
							public void handle(int rC)
							{
								runOnUiThread(new Runnable()
								{
									@Override
									public void run()
									{
										pSPB.setProgress(55);
										findViewById(R.id.st_set_account_1_1_pb).setVisibility(View.INVISIBLE);
										findViewById(R.id.st_set_account_1_1_ok).setVisibility(View.VISIBLE);
										((TextView) findViewById(R.id.st_set_account_1_1_title)).setTextColor(Color.rgb(153, 255, 102));
										findViewById(R.id.st_set_account_1_2).setVisibility(View.VISIBLE);
										findViewById(R.id.st_set_account_1_2_pb).setVisibility(View.VISIBLE);
									}
								});
								if (rC == 1)
									hdlr.sendEmptyMessage(3);
								else
								{
									Message msg = new Message();
									msg.what = -1;
									msg.obj = new String("Authentication failed during Setup in checkAccount.");
									hdlr.sendMessage(msg);
								}
							}
						}, hdlr);
						break;
					}
					case -1 :
					{
						AlertDialog.Builder adb = new AlertDialog.Builder(Thoth.cx);
						adb.setIcon(R.drawable.icon);
						adb.setTitle("Grant access : Denied");
						adb.setMessage("Thoth requires an authenticated channel to communicate with the Thoth server.\n\n Do you want to try again?");
						adb.setCancelable(false);
						adb.setPositiveButton("Yes", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								final Account[] accounts = AccountManager.get(Thoth.cx).getAccounts();
								for (Account account : accounts)
								{
									if (account.hashCode() == Thoth.Settings.USR_DEVICE_ACCOUNT)
									{
										checkAccount(account);
										dialog.dismiss();
									}
								}
							}
						});
						adb.setNegativeButton("No", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								dialog.cancel();
								Main.getInstance().mainHandler.sendEmptyMessage(666);
							}
						});
						Thoth.ad = adb.create();
						Thoth.ad.show();
						break;
					}
				}
			}
		});
		pSPB.setProgress(5);
	}
	
	void connect()
	{
		RequestListener.onReceive(Thoth.REQ.CONNECT, new ThothRequestCallback()
		{
			@Override
			public void progress(int resultCode, int progressValue, final int r)
			{}
			
			@Override
			public void handle(int resultCode)
			{
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						pSPB.setProgress(70);
					}
				});
				if (resultCode == 1)
					checkUser();
				else if (resultCode == -1)
				{
					Message msg = new Message();
					msg.what = -1;
					msg.obj = new String("REQ.CONNECT failed during Setup in connect.");
					hdlr.sendMessage(msg);
				}
			}
		});
	}
	
	void checkUser()
	{
		RequestListener.onReceive(Thoth.REQ.USR_CHECK, new ThothRequestCallback()
		{
			@Override
			public void handle(int resultCode)
			{
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						pSPB.setProgress(75);
					}
				});
				if (resultCode == 1) // User exists
					hdlr.sendEmptyMessage(5);
				else if (resultCode == 2) // User does not exist
					hdlr.sendEmptyMessage(4);
				else
				// Error
				{
					Message msg = new Message();
					msg.what = -1;
					msg.obj = new String("REQ.USR_CHECK failed during Setup in checkUser.");
					hdlr.sendMessage(msg);
				}
			}
			
			@Override
			public void progress(int resultCode, int progressValue, final int r)
			{}
		});
	}
	
	void createUser()
	{
		RequestListener.onReceive(Thoth.REQ.USR_CREATE, new ThothRequestCallback()
		{
			@Override
			public void handle(int resultCode)
			{
				if (resultCode == 1)
				{
					runOnUiThread(new Runnable()
					{
						@Override
						public void run()
						{
							pSPB.setProgress(100);
							findViewById(R.id.st_set_account_1_2_pb).setVisibility(View.GONE);
							findViewById(R.id.st_set_account_1_2_ok).setVisibility(View.VISIBLE);
							((TextView) findViewById(R.id.st_set_account_1_2_title)).setTextColor(Color.rgb(153, 255, 102));
							((TextView) findViewById(R.id.st_set_account_1_1_title)).setTextColor(Color.rgb(153, 255, 102));
							findViewById(R.id.st_set_account_1_ok).setVisibility(View.VISIBLE);
							findViewById(R.id.st_set_account_1_pb1).setVisibility(View.GONE);
							findViewById(R.id.st_set_account_1_pb2).setVisibility(View.GONE);
						}
					});
					hdlr.sendEmptyMessage(50); // Start log capture
				}
				else
				{
					Message msg = new Message();
					msg.what = -1;
					msg.obj = new String("REQ.USR_CREATE failed during Setup in createUser.");
					hdlr.sendMessage(msg);
				}
			}
			
			@Override
			public void progress(int resultCode, int progressValue, final int r)
			{}
		});
	}
	
	void editUser()
	{
		RequestListener.onReceive(Thoth.REQ.USR_EDIT, new ThothRequestCallback()
		{
			@Override
			public void handle(int resultCode)
			{
				if (resultCode == 1) // 1 - User edit OK
				{
					runOnUiThread(new Runnable()
					{
						@Override
						public void run()
						{
							pSPB.setProgress(100);
							findViewById(R.id.st_set_account_1_2_pb).setVisibility(View.GONE);
							findViewById(R.id.st_set_account_1_2_ok).setVisibility(View.VISIBLE);
							((TextView) findViewById(R.id.st_set_account_1_2_title)).setTextColor(Color.rgb(153, 255, 102));
							((TextView) findViewById(R.id.st_set_account_1_1_title)).setTextColor(Color.rgb(153, 255, 102));
							findViewById(R.id.st_set_account_1_ok).setVisibility(View.VISIBLE);
							findViewById(R.id.st_set_account_1_pb1).setVisibility(View.GONE);
							findViewById(R.id.st_set_account_1_pb2).setVisibility(View.GONE);
						}
					});
					hdlr.sendEmptyMessage(50); // Start log capture
				}
				else
				{
					Message msg = new Message();
					msg.what = -1;
					msg.obj = new String("REQ.USR_EDIT failed during Setup in editUser.");
					hdlr.sendMessage(msg);
				}
			}
			
			@Override
			public void progress(int resultCode, int progressValue, final int r)
			{}
		});
	}
	
	void captureLogs()
	{
		try
		{
			runOnUiThread(new Runnable()
			{
				@Override
				public void run()
				{
					((TextView) findViewById(R.id.st_set_account_1_title)).setTextColor(Color.rgb(153, 255, 102));
					findViewById(R.id.st_set_account_1_2).setVisibility(View.GONE);
					findViewById(R.id.st_set_account_1_1).setVisibility(View.GONE);
					findViewById(R.id.st_set_account_2).setVisibility(View.VISIBLE);
					findViewById(R.id.st_set_account_2_1).setVisibility(View.VISIBLE);
					findViewById(R.id.st_set_account_2_2).setVisibility(View.VISIBLE);
					findViewById(R.id.st_set_account_2_3).setVisibility(View.VISIBLE);
					findViewById(R.id.st_set_account_2_4).setVisibility(View.VISIBLE);
					pSPB = (ProgressBar) findViewById(R.id.st_set_account_2_pb2);
				}
			});
			waitForLogCapture(new ThothRequestCallback()
			{
				@Override
				public void handle(final int resultCode)
				{
					if (resultCode == 1)
					{
						runOnUiThread(new Runnable()
						{
							@Override
							public void run()
							{
								findViewById(R.id.st_set_account_2_2_pb).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_2_2_ok).setVisibility(View.VISIBLE);
								((TextView) findViewById(R.id.st_set_account_2_title)).setTextColor(Color.rgb(153, 255, 102));
								findViewById(R.id.st_set_account_2_pb1).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_2_pb2).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_2_ok).setVisibility(View.VISIBLE);
								findViewById(R.id.st_set_account_2_4).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_2_3).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_2_2).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_2_1).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_3).setVisibility(View.VISIBLE);
								findViewById(R.id.st_set_account_3_1).setVisibility(View.VISIBLE);
								pSPB = (ProgressBar) findViewById(R.id.st_set_account_3_pb2);
								pSPB.setMax(0);
								pSPB.setProgress(0);
							}
						});
						RequestListener.onReceive(Thoth.REQ.LOG_CREATE, new ThothRequestCallback()
						{
							@Override
							public void handle(int rC)
							{
								switch (rC)
								{
									case 1 :
									case 4 :
									{
										runOnUiThread(new Runnable()
										{
											@Override
											public void run()
											{
												findViewById(R.id.st_set_account_3_1_pb).setVisibility(View.GONE);
												findViewById(R.id.st_set_account_3_1_ok).setVisibility(View.VISIBLE);
												((TextView) findViewById(R.id.st_set_account_3_1_title)).setTextColor(Color.rgb(153, 255, 102));
												pSPB.setProgress(pSPB.getMax());
											}
										});
										captureAnalytics();
										break;
									}
									case -1 :
									{
										Message msg = new Message();
										msg.what = -1;
										msg.obj = new String("REQ.LOG_CREATE failed during Setup in captureLogs.");
										hdlr.sendMessage(msg);
										break;
									}
								}
							}
							
							@Override
							public void progress(final int rC, final int rV, final int r)
							{
								if (rC == -50)
								{
									runOnUiThread(new Runnable()
									{
										@Override
										public void run()
										{
											pSPB.setMax(pSPB.getMax() + rV);
										}
									});
								}
								else
								{
									runOnUiThread(new Runnable()
									{
										@Override
										public void run()
										{
											pSPB.setProgress(pSPB.getProgress() + rV);
											TextView tvs = (TextView) findViewById(R.id.st_set_account_3_1_title);
											tvs.setText("");
											tvs.setText("Log Upload (" + pSPB.getProgress() + "/" + pSPB.getMax() + ")");
										}
									});
								}
							}
						});
					}
					else
					{
						Message msg = new Message();
						msg.what = -1;
						msg.obj = new String("REQ.LOG_CREATE failed during Setup in captureLogs.");
						hdlr.sendMessage(msg);
					}
				}
				
				@Override
				public void progress(int resultCode, int progressValue, final int r)
				{}
			});
		}
		catch (Exception e)
		{
			ThothLog.e(e);
		}
	}
	
	void waitForLogCapture(final ThothRequestCallback callback)
	{
		new Thread()
		{
			@Override
			public void run()
			{
				new Runnable()
				{
					@Override
					public void run()
					{
						hdlr.sendEmptyMessageDelayed(-888, 600000);
						while (!captureTimeout)
						{
							try
							{
								runOnUiThread(new Runnable()
								{
									@Override
									public void run()
									{
										if (!SETUP_CALL_CAPTURE)
										{
											((TextView) findViewById(R.id.st_set_account_2_1_title)).setTextColor(Color.rgb(153, 255, 102));
											findViewById(R.id.st_set_account_2_1_pb).setVisibility(View.GONE);
											findViewById(R.id.st_set_account_2_1_ok).setVisibility(View.VISIBLE);
											findViewById(R.id.st_set_account_2_2_pb).setVisibility(View.VISIBLE);
										}
										if (!SETUP_MSGS_CAPTURE)
										{
											((TextView) findViewById(R.id.st_set_account_2_2_title)).setTextColor(Color.rgb(153, 255, 102));
											findViewById(R.id.st_set_account_2_2_pb).setVisibility(View.GONE);
											findViewById(R.id.st_set_account_2_2_ok).setVisibility(View.VISIBLE);
											findViewById(R.id.st_set_account_2_3_pb).setVisibility(View.VISIBLE);
										}
										if (!SETUP_MSGM_CAPTURE)
										{
											((TextView) findViewById(R.id.st_set_account_2_3_title)).setTextColor(Color.rgb(153, 255, 102));
											findViewById(R.id.st_set_account_2_3_pb).setVisibility(View.GONE);
											findViewById(R.id.st_set_account_2_3_ok).setVisibility(View.VISIBLE);
											findViewById(R.id.st_set_account_2_4_pb).setVisibility(View.VISIBLE);
										}
										if (!SETUP_DATA_CAPTURE)
										{
											((TextView) findViewById(R.id.st_set_account_2_4_title)).setTextColor(Color.rgb(153, 255, 102));
											findViewById(R.id.st_set_account_2_4_pb).setVisibility(View.GONE);
											findViewById(R.id.st_set_account_2_4_ok).setVisibility(View.VISIBLE);
										}
									}
								});
								if (!SETUP_CALL_CAPTURE && !SETUP_MSGS_CAPTURE && !SETUP_MSGM_CAPTURE && !SETUP_DATA_CAPTURE)
									captureTimeout = true;
								else
									Thread.sleep(500);
							}
							catch (InterruptedException e)
							{
								ThothLog.e(e);
							}
						}
						if (!SETUP_CALL_CAPTURE && !SETUP_MSGS_CAPTURE && !SETUP_MSGM_CAPTURE && !SETUP_DATA_CAPTURE)
						{
							captureTimeout = false;
							hdlr.removeMessages(-888);
							callback.handle(1);
							return;
						}
						else if (captureTimeout) // Timeout
						{
							captureTimeout = false;
							callback.handle(-1);
							return;
						}
					}
				}.run();
			};
		}.start();
	}
	
	void captureAnalytics()
	{
		runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				findViewById(R.id.st_set_account_3_2).setVisibility(View.VISIBLE);
				pSPB.setMax(0);
				pSPB.setProgress(0);
			}
		});
		RequestListener.onReceive(Thoth.REQ.LOG_ANALYTICS, new ThothRequestCallback()
		{
			@Override
			public void handle(int resultCode)
			{
				switch (resultCode)
				{
					case 1 :
					{
						runOnUiThread(new Runnable()
						{
							@Override
							public void run()
							{
								findViewById(R.id.st_set_account_3_2).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_3_1).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_3_ok).setVisibility(View.VISIBLE);
								findViewById(R.id.st_set_account_3_pb1).setVisibility(View.GONE);
								findViewById(R.id.st_set_account_3_pb2).setVisibility(View.GONE);
								((TextView) findViewById(R.id.st_set_account_3_title)).setTextColor(Color.rgb(153, 255, 102));
								Thoth.Settings.APP_SETUP = false; // Setup is complete.
								Thoth.Settings.write();
								promptGoogleMailSync(); // Ask user if they want to enable GMail sync
							}
						});
						break;
					}
					case -1 :
					{
						hdlr.sendEmptyMessage(-1);
						break;
					}
				}
			}
			
			@Override
			public void progress(final int resultCode, final int progressValue, final int r)
			{
				if (resultCode == -50)
				{
					runOnUiThread(new Runnable()
					{
						@Override
						public void run()
						{
							pSPB.setMax(pSPB.getMax() + progressValue);
						}
					});
				}
				else
				{
					runOnUiThread(new Runnable()
					{
						@Override
						public void run()
						{
							pSPB.setProgress(pSPB.getProgress() + progressValue);
							TextView tvs = (TextView) findViewById(R.id.st_set_account_3_2_title);
							tvs.setText("");
							tvs.setText("Analytics Download (" + pSPB.getProgress() + "/" + pSPB.getMax() + ")");
						}
					});
				}
			}
		});
	}
	
	void promptGoogleMailSync()
	{
		bt.setVisibility(View.GONE);
		pb.setVisibility(View.GONE);
		sF.setDisplayedChild(3);
		gmbt = (Button) findViewById(R.id.gmail_setup_bt);
		gmbtno = (Button) findViewById(R.id.gmail_setup_btno);
		gmbt.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				gmbt.setVisibility(View.GONE);
				gmbtno.setVisibility(View.GONE);
				Thoth.createThothAsContact(new ThothCallback()
				{
					@Override
					public void handle(boolean result)
					{
						if (result)
						{
							Thoth.Settings.APP_ENABLE_GoMAIL = true;
							Thoth.Settings.write();
							gmbt.setVisibility(View.VISIBLE);
							gmbt.setText("Connected");
							if (!Thoth.Settings.APP_ENABLE_GoCAL)
								promptGoogleCalendarSync();
							else
								Main.getInstance().mainHandler.sendEmptyMessage(2);
						}
						else
							promptGoogleCalendarSync();
					}
				});
			}
		});
		gmbtno.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (!Thoth.Settings.APP_ENABLE_GoCAL)
					promptGoogleCalendarSync();
				else
					Main.getInstance().mainHandler.sendEmptyMessage(2);
			}
		});
	}
	
	void promptGoogleCalendarSync()
	{
		bt.setVisibility(View.GONE);
		pb.setVisibility(View.GONE);
		sF.setDisplayedChild(4);
		gcbt = (Button) findViewById(R.id.calendar_setup_bt);
		gcbtno = (Button) findViewById(R.id.calendar_setup_btno);
		gcbt.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				gcbt.setVisibility(View.GONE);
				gcbtno.setVisibility(View.GONE);
				((TextView) findViewById(R.id.st_calendar_msg)).setText(R.string.st_calendar_msg_2);
				final HashMap<String, Integer> calendarMap = new HashMap<String, Integer>();
				final Uri CALENDAR = (Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.ECLAIR_MR1) ? Uri.parse("content://com.android.calendar") : Uri.parse("content://calendar");
				Cursor c = null;
				try
				{
					c = Thoth.cx.getContentResolver().query(Uri.withAppendedPath(CALENDAR, "calendars"), new String[]{"_id", "displayname", "_sync_account", "_sync_account_type"}, null, null, "displayname ASC");
					while (c != null && c.moveToNext())
					{
						if (c.getString(3).equalsIgnoreCase("com.google") && c.getString(2).equalsIgnoreCase(Thoth.Settings.USR_DEVICE_ACCOUNT_EMAIL))
							calendarMap.put(c.getString(1), c.getInt(0));
					}
				}
				catch (IllegalArgumentException e)
				{
					ThothLog.e(e);
					Main.getInstance().mainHandler.sendEmptyMessage(2);
				}
				finally
				{
					if (c != null)
						c.close();
				}
				final List<String> calendarNames = new ArrayList<String>();
				for (String calendar : calendarMap.keySet())
					calendarNames.add(calendar);
				ListView calendarList = (ListView) findViewById(R.id.st_calendar_list);
				calendarList.setAdapter(new ArrayAdapter<String>(Thoth.cx, android.R.layout.simple_expandable_list_item_1, calendarNames));
				calendarList.setDivider(getResources().getDrawable(R.drawable.row_gradient1));
				calendarList.setDividerHeight(1);
				calendarList.setOnItemClickListener(new OnItemClickListener()
				{
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
					{
						if (calendarMap.containsKey(calendarNames.get(pos)))
						{
							Thoth.Settings.USR_DEVICE_ACCOUNT_CALENDAR = calendarMap.get(calendarNames.get(pos));
							Thoth.Settings.APP_ENABLE_GoCAL = true;
							Thoth.Settings.write();
							Main.getInstance().mainHandler.sendEmptyMessage(2);
						}
					}
				});
			}
		});
		gcbtno.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Main.getInstance().mainHandler.sendEmptyMessage(2);
			}
		});
	}
}
